﻿using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevTeam;
using Impinj.OctaneSdk;
using System;
using System.Collections.Generic;

namespace ConfExpert.Forms.Depo
{
    public partial class RfidWriteEpc : XPopupForm
    {
        // Create an instance of the SpeedwayReader class.
        static SpeedwayReader Reader = new SpeedwayReader();

        public RfidWriteEpc()
        {
            InitializeComponent();
        }

        private void RfidWriteEpc_Load(object sender, EventArgs e)
        {
            
            gridControl1.DataSource = rfidsC;
            gridView1.OptionsView.ShowViewCaption = false;
            gridView1.OptionsView.ShowGroupPanel = false;
            //gridView1.Columns[0].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            //gridView1.Columns[0].DisplayFormat.FormatString = "X";
            gridView1.Columns[0].Caption = "EPC";

            btnConnect.ItemClick += BtnConnect_ItemClick;
            btnRead.Click += new EventHandler(btnRead_Click);
            btnWrite.Click += new EventHandler(btnWrite_Click);
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(RfidWriteEpc_FormClosing);
            btnNext.Click += new EventHandler(btnNext_Click);
            memoEdit1.Properties.HideSelection = false;
        }

        private void BtnConnect_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            throw new NotImplementedException();
        }

        void btnNext_Click(object sender, EventArgs e)
        {
            Next();
        }

        private void Next()
        {
            if (!memoEdit1.Text.EndsWith(Environment.NewLine))
                memoEdit1.Text += Environment.NewLine;

            if (memoEdit1.SelectionLength == 0)
                if (memoEdit1.SelectionStart == memoEdit1.Text.Length)
                    memoEdit1.SelectionStart = 0;

            int i = 0, cnt = 0, lines = memoEdit1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).Length;
            while (i == 0 && cnt++ < lines)
                i = intParse(birsonraki());
        }

        void btnRead_Click(object sender, EventArgs e)
        {
            rfidsC.Clear();
            gridControl1.DataSource = null;
            gridControl1.DataSource = rfidsC;
        }

        List<string> rfidsC = new List<string>(); //net çıkan
        delegate void AddTagOCallback(List<Tag> tags);
        public void TagsReportedHandler(object sender, TagsReportedEventArgs args)
        {
            Invoke(new AddTagOCallback(AddTag), args.TagReport.Tags);
        }

        private void AddTag(List<Tag> tags)
        {
            foreach (Tag tag in tags)
                if (!rfidsC.Contains(tag.Epc))
                    rfidsC.Add(tag.Epc);
            gridView1.RefreshData();
        }

        void RfidWriteEpc_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            try
            {
                Reader.TagsReported -= new EventHandler<TagsReportedEventArgs>(TagsReportedHandler);
                // Disconnect from the reader.
                Reader.Disconnect();
            }
            catch
            {
            }
        }

        void btnConnect_Click(object sender, EventArgs e)
        {
                try
                {
                    // Connect to the reader.
                    // Replace "SpeedwayR-10-25-32" with your 
                    // reader's host name or IP address.
                    Reader.Connect(AppSession.GateIP);
                    // Configure the reader with the factory deafult settings.
                    Reader.ApplyFactorySettings();
                    

                    Reader.TagsReported += new EventHandler<TagsReportedEventArgs>(TagsReportedHandler);
                    // Clear all reader settings. 
                    Reader.ClearSettings();
                    // Get the factory settings for the reader. We will 
                    // use these are a starting point and then modify 
                    // the settings we're interested in. 
                    Settings settings = Reader.QueryFactorySettings();
                    // Send a report for every tag seen. 
                    settings.Report.Mode = ReportMode.Individual;

                    //settings.Antennas[1].IsEnabled = true;
                    //settings.Antennas[1].TxPowerInDbm = 32;
                    // Include the antenna number in the tag report. 
                    //settings.Report.IncludeAntennaPortNumber = true;
                    settings.LowDutyCycle.IsEnabled = true;
                    settings.LowDutyCycle.EmptyFieldTimeoutInMs = 3000;
                    settings.LowDutyCycle.FieldPingIntervalInMs = 200;

                    // Apply the new settings. 
                    Reader.ApplySettings(settings);
                    // Start reading tags. 

                    Reader.Start();

                }
                catch (Exception Ex)
                {
                    throw Ex;
                }
            
        }

        string birsonraki()
        {
            int bsl = 0;
            if (memoEdit1.SelectionLength > 0)
                bsl = memoEdit1.Text.IndexOf(Environment.NewLine, memoEdit1.SelectionStart) + 2;
            memoEdit1.Select(bsl, memoEdit1.Text.Substring(bsl).IndexOf(Environment.NewLine) + 2);
            return memoEdit1.SelectedText.Trim();
        }

        
        void btnWrite_Click(object sender, EventArgs e)
        {
            //string[] newidsStr = memoEdit1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            Next();
            int NewEpc = intParse(memoEdit1.SelectedText.Trim());

            if(NewEpc == 0)
                XtraMessageBox.Show("Please enter valid EPC values");
            else
            {
                Reader.TagsReported -= new EventHandler<TagsReportedEventArgs>(TagsReportedHandler);

                rfidsC.Clear();
                TagReport tagReport = Reader.QueryTags(0.500);
                foreach (Tag tag in tagReport.Tags)
                {
                    try
                    {
                        // Define how we want to perform the write.
                        ProgramEpcParams epcParams = new ProgramEpcParams();
                        // Use antenna #1.
                        epcParams.AntennaPortNumber = 1;
                        // Write to the first tag we see.
                        // Alternatively, we could choose a specific
                        // tag by EPC or other identifier.
                        epcParams.TargetTag = null; //null: ilk tag e yazar, tag.Epc: belirtilen tag e.
                        epcParams.AccessPassword = null;
                        // Timeout in 5 seconds if the write operation fails.
                        epcParams.TimeoutInMs = 1000;
                        // This is the new EPC we will write to the tag.
                        //string NewEpcBase = "0000-0000-0000-0000-0000-";
                        epcParams.NewEpc = (NewEpc + (chkRaf.Checked ? (int)1e9 : 0)).ToString("d24"); //.ToString("X24") -> "0123-4567-89AB-CDEF-0123-4567";
                        epcParams.IsWriteVerified = true;
                        // Perform the write and check the results.
                        ProgramEpcResult result = Reader.ProgramEpc(epcParams);
                        if (result.WriteResult.Result == AccessResult.Success)
                        {
                            // Show how many words were written to the tag.
                            Notify(String.Format("Tag write successful. {0} words written.", result.WriteResult.NumWordsWritten));
                            // Read back the EPC and print it out.
                            //Notify("Querying tag...");
                            //TagReport report = Reader.QueryTags(1);
                            //Notify(String.Format("Tag EPC: {0}", report.Tags[0].Epc));
                            //spinEdit1.EditValue = ++index;
                            //cnt++;

                            break;
                        }
                    }
                    catch (OctaneSdkException e1)
                    {
                        XtraMessageBox.Show(e1.Message, "Octane SDK exception");
                    }
                    catch (Exception e2)
                    {
                        XtraMessageBox.Show(e2.Message, "Exception");
                    }
                }

                btnRead.PerformClick();
                Reader.Start();
                Reader.TagsReported += new EventHandler<TagsReportedEventArgs>(TagsReportedHandler);


            }

        }
    }
}